<?php
/**
 * Authority Control
 * User: zng
 * Date: 2019/11/20
 * Time: 13:39
 */
namespace app\admin\behavior;

use app\admin\service\Permission;
use gmars\rbac\Rbac;
use app\exceptions\{
    OrdinaryException,PowerException
};
use think\{
    Exception,Request
};

Class AuthorityControl {

    /**
     * @throws OrdinaryException
     * @throws PowerException
     */
    public function run(Permission $service, Request $request)
    {
        $pathInfo = $service->path($request);
        $adminInfo = $request->userInfo;
        $config = config('permission.');
        if ( !$adminInfo ) {
            if ( ! in_array($pathInfo['path'], $config['exclude']) &&
                ! in_array($pathInfo['action'], $config['currency_exclude_action']) &&
                ! in_array($pathInfo['group_controller'], $config['exclude_controller']) ) {
                throw new PowerException();
            }
        } else{
            if ( $adminInfo['type'] != 1 &&
                ! in_array($pathInfo['path'], $config['exclude']) &&
                ! in_array($pathInfo['action'], $config['currency_exclude_action']) &&
                ! in_array($pathInfo['group_controller'], $config['exclude_controller']) ) {
                try{
                    if ( false === (new Rbac())->can($pathInfo['path']) ) {
                        throw new PowerException();
                    }
                } catch ( Exception $exception ) {
                    throw new OrdinaryException($exception->getMessage());
                }
            }
        }
    }

}